<template>
  <div id="cornerComment" v-if="dialogVisible">
    <div class="cornerComment-in">
      <div class="cornerComment-in-title">
        <span>摇号</span>
        <span class="el-icon-circle-close close-Btn-line" @click="closePOpup"></span>
      </div>
      <div class="commentBody">
        <div class="bg" :style="{backgroundImage:'url('+bgJpg+')',backgroundSize:'cover',backgroundPosition:'center'}"
             ref="boxCanvas">
          <div class="content-box" v-show="showCanvasAnimate">
            <!--          左侧滚动-->
            <div id="myCanvasContainer" class="content-left">
              <canvas width="500" height="700" id="myCanvas" ref="canvas">
                <p>换个现代浏览器吧！</p>
              </canvas>
              <div id="tags">
                <ul>
                  <li v-for="(tag, index) in members" :key="index">
                    <a href="javascript:;" target="_blank" style="height: auto;font-size: 60px;font-weight: bold;">
                      {{ tag.name }}
                    </a>
                  </li>
                </ul>
              </div>
            </div>
            <!--          右侧按键-->
            <div class="content-right">
              <div class="showbox-in">
                <div class="showbox-in-title">{{ detailOption ? detailOption.name : '' }}</div>
                <div class="showbox-in-img">
                  <div id="qrcode"></div>
                </div>
                <p>参与人扫码进入选号</p>
                <div class="showbox-in-number">
                  <p class="showbox-in-number-list">盲号总数：<span>{{ detailOption ? detailOption.number : 0 }}</span></p>
                  <p class="showbox-in-number-list shownumberClass" @click="showUserNumber()">当前已选号码人数：
                    <count-to :startVal='startVal' :endVal='number' :duration='1000'></count-to>
                  </p>
                </div>
                <div class="showbox-in-btn">
                  <span @click="getStarFn" class="check-submit">开盲</span>
                </div>
                <span @click="backlist" class="backclose-popup">返回</span>
              </div>
            </div>
          </div>
        </div>
        <div class="showbox" v-if="getNumber">
          <div class="showbox-in-number-box">
            <div class="showbox-in-number">
              <p class="showbox-in-number-list">盲号总数：<span>{{ detailOption ? detailOption.number : 0 }}</span></p>
            </div>
            <div class="loading-number mb-20" v-show="loadingStatus">
              请稍后，生成中<i class="el-icon-loading"></i>
            </div>
            <div class="showbox-in-btn">
              <span @click="getNumberListFn" class="check-submit"
                    :class="loadingStatus?'check-submit-not':''">生成随机号</span>
            </div>
            <span @click="backlist">返回</span>
          </div>
        </div>
        <div class="showbox" v-if="showUserNumberStatus">
          <div class="showbox-in-userlist">
            <div class="number-list-box">
              <div>{{ showDrawStatus ? '开盲明细' : '当前号码详情' }}</div>
              <el-table
                  :data="tableData"
                  height="400"
                  border
                  style="width: 100%"
                  size="small"
                  header-cell-class-name="table-text-c"
                  cell-class-name="table-text-c">
                <el-table-column
                    label="序列号"
                    width="80"
                    :key="1">
                  <template slot-scope="scope">
                    {{ scope.$index + 1 }}
                  </template>
                </el-table-column>
                <el-table-column
                    prop="code"
                    label="号码"
                    :key="2">
                </el-table-column>
                <el-table-column
                    label="开盲结果"
                    :key="3"
                    v-if="showDrawStatus">
                  <template slot-scope="scope">
                    <!--                    detailOption type 0 家长 1 教职工-->
                    {{ scope.row.prize.name}}
                  </template>
                </el-table-column>
                <el-table-column
                    prop="address"
                    label="用户"
                    :key="4">
                  <template slot-scope="scope">
                    <!--                    detailOption type 0 家长 1 教职工-->
                    {{ detailOption.type == 1 ? scope.row.users.realname : scope.row.student.name }}
                  </template>
                </el-table-column>
              </el-table>
            </div>
            <span @click="closeDrawPage" class="back-btn-popup mt-20">返回</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>

import bgJpg from '@/assets/imageAdmin/bg.jpg'
import countTo from 'vue-count-to'
import QRCode from 'qrcodejs2'

export default {
  props: ['visible', 'drawId'], // commoent 学生点评 collection 学生采集
  components: {
    countTo
  },
  data() {
    return {
      showDrawStatus: false,
      tableData: [],
      dialogVisible: false,
      showBox: false,
      running: false,
      awards: [],
      currentAward: 0,
      result: [],
      players: [],
      batchPlayers: [],
      members: [],
      bgJpg: bgJpg,
      number: 0,
      startVal: 0,
      timeNumberFn: null,
      isFullscreen: false,
      dilogStatusFn: true, //
      httpUrlInfo: '',
      getNumber: true,
      // drawId: 13,
      showCanvasAnimate: false,
      detailOption: null,
      loadingStatus: false,
      showUserNumberStatus: false
    }
  },
  watch: {
    visible() {
      this.dialogVisible = this.visible
      if (this.visible) {
        this.InitFn()
      } else {
        this.showUserNumberStatus = false;
        this.showCanvasAnimate = false;
        this.showDrawStatus = false;
        this.tableData = [];
        this.getNumber = true;
        this.loadingStatus = false;
        clearInterval(this.timeNumberFn)
      }
    }
  },
  created() {
  },
  methods: {
    // 关闭弹窗
    closePOpup() {
      this.$emit('update:visible', false)
    },
    // async InitFn() {
    //   let data = await this.$fetch(this.api.admin_student_edit, {
    //     id: this.studentId
    //   })
    //   if (!data.code) {
    //     this.userInfo = data.vo
    //   } else {
    //     this.$message.error(data.msg)
    //   }
    // },

    // 请求抽奖数据
    getDrawInfo() {
      let that = this;
      this.$fetch(this.api.giftDraw.edit, {id: this.drawId}).then(res => {
        if (res.code === 0) {
          this.detailOption = res.detail
          let membersList = []
          for (let i in res.code_list) {
            membersList.push({
              'name': res.code_list[i].code + '号',
              'id': Number(i) + 1
            })
          }
          // members 参与者号码 [{"name": "01号", "id": 1}]
          this.members = this.copy(membersList)
          let canvas = this.$refs.canvas
          canvas.width = this.$refs.boxCanvas.offsetWidth - 500
          // canvas.height = document.body.offsetHeight - 170
          this.timeNumberFn = setInterval(() => {
            that.getNumberCode()
          }, 1000)
          this.$nextTick(function () {
            this.init()
          })
          // document.body.addEventListener('keyup', this.onKeyup) // 空格建
          this.qrcode(res.detail)
        } else {
          this.$message({
            message: res.msg,
            type: 'error'
          })
        }
      })
    },
    InitFn() {
      this.$fetch(this.api.system_setting, {}).then(res => {
        if (!res.code) {
          this.httpUrlInfo = res.vo.url;
          this.getDrawInfo()
        } else {

        }
      })
    },
    // 生成二维码,家长，教职工不同的页面参数id type类型
    qrcode(option) {
      let that = this;
      let qrcode = new QRCode('qrcode', {
        width: 200,
        height: 200, // 高度
        text: that.httpUrlInfo + '/program/#/Lottery?id=' + this.drawId + '&type=' + option.type
      })
      console.log(qrcode)
    },
    // 开始抽奖
    getStarFn() {
      let that = this
      // if (!this.number) {
      //   this.$confirm('当前选号码人数为空', '提示', {
      //     confirmButtonText: '确定',
      //     showCancelButton: false,
      //     type: 'warning'
      //   }).then(() => {
      //   }).catch(() => {
      //   });
      //   return
      // }
      if(!this.number){
        this.$confirm('当前已选择号码人数为0，不能开盲！', '提示', {
          confirmButtonText: '确定',
          showCancelButton:false,
          type: 'warning'
        }).then(() => {
        }).catch(() => {
        });
        return
      }
      if (this.number < this.detailOption.number) {
        this.$confirm('已选号码人数与盲号个数不符，是否确定开始抽签?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          clearInterval(that.timeNumberFn)
          that.gottoDrawFn()
        }).catch(() => {
        });
      }
      if(this.number === this.detailOption.number){
        this.$confirm('是否立即开始抽签?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          clearInterval(that.timeNumberFn)
          that.gottoDrawFn()
        }).catch(() => {
        });
      }
    },
    gottoDrawFn() {
      let that = this
      this.dilogStatusFn = false
      this.start()
      setTimeout(() => {
        that.showDrawStatus = true;
        that.showUserNumberStatus = true;
        that.stop()
      }, 3000)
      // 抽签最后结果
      this.$fetch(this.api.giftDraw.end, {id: this.drawId}).then(res => {
        if (res.code === 0) {
          let list_ = []
          for (let i in res.list) {
            res.list[i].code = Number(res.list[i].code) < 10 ? ('0' + Number(res.list[i].code)) + '号' : res.list[i].code + '号'
            list_.push(res.list[i])
          }
          this.tableData = this.copy(list_)
          setTimeout(() => {
            that.showDrawStatus = true;
            that.showUserNumberStatus = true;
            that.stop()
            that.$emit('InitFn')
          }, 3000)
        } else {
          this.$message({
            message: res.msg,
            type: 'error'
          })
        }
      })
    },
    // 点击抽奖
    toggle: function () {
      if (this.running) {
        this.stop()
      } else {
        this.start()
      }
    },
    getSpeed: function () {
      return [0.1 * Math.random() + 0.01, -(0.1 * Math.random() + 0.01)]
    },
    start: function () {
      this.running = true
      TagCanvas.SetSpeed('myCanvas', [5, 1])
    },
    stop: function () {
      this.running = false
      TagCanvas.SetSpeed('myCanvas', this.getSpeed())

      TagCanvas.Reload('myCanvas')
    },
    onNext: function () {
      this.batchPlayers = []
      if (this.currentAward < this.awards.length - 1) {
        this.currentAward += 1
      }
    },
    getRandomInt: function (min, max) {
      min = Math.ceil(min)
      max = Math.floor(max)
      return Math.floor(Math.random() * (max - min + 1)) + min
    },
    init: function () {
      try {
        TagCanvas.Start('myCanvas', 'tags', {
          textColour: "#fff",
          dragControl: 1,
          decel: 0.6,
          textHeight: 40,
          minSpeed: 0.02,
          maxSpeed: 0.4,
          outlineThickness: 0,
          depath: 2,
          initial: [
            0.1 * Math.random() + 0.01,
            -(0.1 * Math.random() + 0.01)
          ] // 配置旋转速度
        })
      } catch (e) {
        // something went wrong, hide the canvas container
        document.getElementById('myCanvasContainer').style.display =
            'none'
      }
    },
    onReplay: function () {
      var vm = this
      this.$confirm('重新抽奖会清空当前奖项的结果，无法撤销！', '确定要重新抽奖吗？', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function () {
        vm.batchPlayers = []
        var p = vm.result.splice(vm.currentAward, 1, [])
        vm.players = vm.players.concat(p[0])
        localStorage.setItem('players', JSON.stringify(vm.players))
        localStorage.setItem('result', JSON.stringify(vm.result))
      })
    },
    onKeyup: function (e) {
      console.log(e)
      // 空格或回车键
      if (e.keyCode === 13 || e.keyCode === 32) {
        this.$refs.action.$el.click()
      }
    },
    copy(obj) {
      return JSON.parse(JSON.stringify(obj))
    },
    onKick: function (player) {
      var vm = this
      var index = vm.result[vm.currentAward].indexOf(player)
      this.$confirm('去掉后可继续抽一名', '去掉这名中奖者吗？', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function () {
        if (vm.batchPlayers.indexOf(player) > -1) {
          vm.batchPlayers.splice(vm.batchPlayers.indexOf(player), 1)
        }
        vm.result[vm.currentAward].splice(index, 1)
        localStorage.setItem('result', JSON.stringify(vm.result))
      })
    },
    closeDrawPage() {
      if (!this.showDrawStatus) {
        this.showUserNumberStatus = false;
      } else {
        this.backlist()
      }
    },
    backlist() {
      this.$emit('update:visible', false)
    },
    // 获取抽奖人选中号码数量
    getNumberCode() {
      if (this.number >= this.detailOption.number) {
        clearInterval(this.timeNumberFn)
      } else {
        this.prizeCodeFn()
      }
    },
    prizeCodeFn() {
      // draw_id 抽奖id status 1
      this.$fetch(this.api.giftDraw.prizeCode, {
        draw_id: this.drawId,
        status: 1,
        loadingStatus: 1
      }).then(res => {
        if (res.code === 0) {
          this.startVal = this.copy(this.number)
          this.number = res.list.total;
          this.tableData = this.copy(res.list.data)
        } else {
        }
      })
    },
    getNumberListFn() {
      let that = this;
      this.loadingStatus = true;
      setTimeout(() => {
        that.showCanvasAnimate = true;
        that.getNumber = false;
      }, 1000)
    },
    showUserNumber() {
      this.showUserNumberStatus = true;
    }
  },
  mounted() {
  }
}
</script>
<style scoped>
#cornerComment {
  height: 100vh;
  width: 100%;
  position: fixed;
  top: 0;
  left: 0;
  background: rgba(0, 0, 0, .5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9;
}

.cornerComment-in {
  width: 98%;
  height: 95%;
  background: #fff;
  display: flex;
  flex-direction: column;
  border-radius: 5px;
}

.cornerComment-in-title {
  height: 50px;
  display: flex;
  align-items: center;
  border-bottom: 1px solid #ddd;
  font-size: 24px;
}

.cornerComment-in-title span {
  padding: 0 10px;
}

.cornerComment-in-title span:first-child {
  flex: 1;
  font-size: 16px;
}

.cornerComment-in-footer {
  height: 50px;
  border-top: 1px solid #ddd;
  display: flex;
  align-items: center;
  padding: 0 10px;
  justify-content: center;
}

.commentBody {
  flex: 1;
  overflow-y: auto;
  background: #fff;
  position: relative;
}

.close-Btn-line {
  cursor: pointer;
}

.infobox-user-left img {
  width: 90px;
  height: auto;
  box-shadow: 0 4px 8px #ddd;
}

.progress-list span {
  display: block;
  width: 53px;
  padding-right: 20px;
  text-align: right;
  color: #777;
}

.infobox-right-left-userline span {
  display: block;
  width: 5px;
  height: 15px;
  border-radius: 2px;
  background: #1b8de5;
  margin-right: 10px;
}

.infobox-user-right p {
  margin-bottom: 6px;
  color: #444;
}


.progress-list-tips-list span {
  display: block;
  width: 4px;
  height: 4px;
  border-radius: 2px;
  background: #0066b5;
  margin-right: 5px;
}

.bg {
  width: 100%;
  height: 100%;
  position: relative;
}

a {
  color: #fff;
}

.buttons {
  position: absolute;
  bottom: 10px;
  width: 100%;
  display: flex;
  justify-content: flex-start;
  align-items: center;
}

.next {
  font-size: 40px;
  color: #fff;
  line-height: 1.5;
  padding: 20px;
  text-align: center;
  position: absolute;
  width: 100%;
}

.next .title {
  color: yellow;
}

.el-select {
  width: 120px;
  margin-right: 10px;
}

.batch {
  position: absolute;
  width: 80%;
  display: flex;
  justify-content: center;
  flex-wrap: wrap;
  top: 50%;
  color: #fff;
  left: 50%;
  transform: translate(-50%, -50%);
  overflow-y: auto;
  height: 600px;
  background: rgba(0, 0, 0, .5);
  border-radius: 5px;
  box-shadow: 0 0 10px #333;
  padding: 10px;
}

.player-txt {
  font-size: 26px;
  color: #c70000;
}

.player {
  display: inline-block;
  text-align: center;
  font-size: 60px;
  width: 200px;
  background: #fff;
  line-height: 40px;
  color: #000;
  margin: 5px;
  border-radius: 10px;
  box-shadow: 0 5px 10px rgba(0, 0, 0, 0.8);
  padding: 10px 0;
  height: 100px;
}

.lucky-dog {
  display: inline-block;
  font-size: 60px;
  text-align: center;
  width: 200px;
  background: #fff;
  line-height: 60px;
  color: #000;
  margin: 5px;
  border-radius: 10px;
  box-shadow: 0 5px 10px rgba(0, 0, 0, 0.8);
  padding: 5px 0;
}

.result {
  width: 200px;
  position: absolute;
  right: 10px;
  top: 100px;
  color: #fff;
  line-height: 1.5;
  font-size: 60px;
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}

.showbox {
  position: absolute;
  height: 100%;
  width: 100%;
  top: 0;
  left: 0;
  background: rgba(0, 0, 0, .3);
  display: flex;
  justify-content: center;
  align-items: center;
}

.showbox-in {
  background: rgba(255, 255, 255, .9);
  border-radius: 10px;
  padding: 20px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  text-align: center;
  width: 500px;
  height: 600px;
  box-shadow: 0 0 10px #ddd;
  font-size: 24px;
}

.showbox-in-number-box {
  background: rgba(255, 255, 255, .9);
  border-radius: 10px;
  padding: 20px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  text-align: center;
  width: 400px;
  height: 300px;
  box-shadow: 0 0 10px #ddd;
  font-size: 24px;
}

.showbox-in-userlist {
  background: #fff;
  border-radius: 10px;
  padding: 20px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  text-align: center;
  box-shadow: 0 0 10px #ddd;
  font-size: 24px;
}

.showbox-in #qrcode {
  width: 216px;
  box-shadow: 0 4px 10px #999;
  border-radius: 5px;
  margin-bottom: 10px;
  border: 8px solid #fff;
}

.showbox-in-title {
  font-weight: bold;
  margin-bottom: 20px;
}

.showbox-in-btn {
  padding-top: 10px;
}

.check-submit {
  background: #E6A23C;
  color: #fff;
  border-radius: 5px;
  padding: 14px 40px;
  cursor: pointer;
  box-shadow: 0 4px 10px #eca32e;
  display: block;
  margin-bottom: 20px;
}

.check-submit-not {
  background: #ddd;
  box-shadow: 0 4px 10px #ddd;
  cursor: not-allowed
}

.showbox-in-number {
  padding: 30px 0;
  font-weight: bold;
}

.showbox-in-number span {
  color: #ff0000;
  font-weight: bold;
  font-size: 28px;
}

.gobackBtn {
  position: absolute;
  top: 20px;
  left: 20px;
  color: #fff;
  font-size: 24px;
  font-weight: bold;
  z-index: 9999;
  cursor: pointer;
}

.content-box {
  display: flex;
  height: 100%;
}

.content-left {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
}

.content-right {
  width: 500px;
  height: 100%;
  justify-content: center;
  padding-right: 10px;
  align-items: center;
  display: flex;
}

.loading-number {
  color: red;
}

.disableBtn {

}

.number-list-box {
  width: 500px;
}

.back-btn-popup {
  border: 1px solid #ddd;
  border-radius: 5px;
  font-size: 22px;
  padding: 5px 20px;
  cursor: pointer;
}

.shownumberClass {
  cursor: pointer;
}

.shownumberClass:hover {
  text-decoration: underline;
}

.backclose-popup {
  cursor: pointer;
}
</style>


